//https://leetcode.cn/submissions/detail/560668901/
class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        using ll = long long;
        ll l = 0, r = 0;
        for (int i = 0; i < arr.size(); i++)
        {
            if (abs(arr[i] - x) < abs(arr[l] - x))l = i;
        }
        vector<int> ans;
        ans.push_back(arr[l]); r = l + 1, l--, k--;
        while (k)
        {
            while (l < 0 && k)ans.push_back(arr[r]), r++, k--;
            while (r >= arr.size() && k)ans.push_back(arr[l]), l--, k--;
            if (!k)break;
            if (abs(arr[l] - x) <= abs(arr[r] - x))ans.push_back(arr[l]), l--;
            else ans.push_back(arr[r]), r++;
            k--;
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
};